package com.chuantou.yuba.ui.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.NetworkImageView;
import com.chuantou.yuba.R;
import com.chuantou.yuba.adapter.NewsListAdapter;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.BaseGsonRequest;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.NewsAdTO;
import com.chuantou.yuba.api.to.NewsDataTO;
import com.chuantou.yuba.api.to.NewsListTO;
import com.chuantou.yuba.api.to.NewsTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.dao.CacheDao;
import com.chuantou.yuba.pojo.Cache;
import com.chuantou.yuba.ui.GiftActivity;
import com.chuantou.yuba.ui.LoginActivity;
import com.chuantou.yuba.ui.NearFishingActivity;
import com.chuantou.yuba.ui.NewsDetailActivity;
import com.chuantou.yuba.ui.TrendsAllActivity;
import com.chuantou.yuba.ui.TrendsNearActivity;
import com.chuantou.yuba.ui.widget.ChildViewPager;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.BitmapBinder;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.LoadCacheTask;
import com.chuantou.yuba.util.UiUtil;
import com.chuantou.yuba.util.ViewHolder;
import com.viewpagerindicator.IconPageIndicator;
import com.viewpagerindicator.IconPagerAdapter;

/**
 * 首页资讯列表fragment
 * 
 * @author dl1001
 * 
 */
public class NewsListFragment extends PaginationListFragment<NewsDataTO> implements OnClickListener {
	private View mHeaderView;
	private ChildViewPager mAdViewPager;
	private IconPageIndicator mIconPageIndicator;
	private String mNewsListUrl = UriHelper.getNewsListUrl();
	private NewsListAdapter mListAdapter;
	private NewsAdAdapter mAdAdapter;

	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View contentView = super.onCreateView(inflater, container, savedInstanceState);
		if (mHeaderView == null) {
			mHeaderView = inflater.inflate(R.layout.news_header, null);
			mHeaderView.findViewById(R.id.menu_square).setOnClickListener(this);
			mHeaderView.findViewById(R.id.menu_near).setOnClickListener(this);
			mHeaderView.findViewById(R.id.menu_fishing).setOnClickListener(this);
			mHeaderView.findViewById(R.id.menu_gift).setOnClickListener(this);
			mAdViewPager = (ChildViewPager) mHeaderView.findViewById(R.id.viewpager);
			mIconPageIndicator = (IconPageIndicator) mHeaderView.findViewById(R.id.indicator);
			mAdAdapter = new NewsAdAdapter();
			mAdViewPager.setAdapter(mAdAdapter);
			mIconPageIndicator.setViewPager(mAdViewPager);
			mListView.addHeaderView(mHeaderView);
			mListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					NewsTO newsTO = (NewsTO) parent.getItemAtPosition(position);
					Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
					intent.putExtra(Constants.EXTRA_DATA, newsTO);
					startActivity(intent);
				}
			});
			mAdViewPager.setOnSingleTouchListener(new ChildViewPager.OnSingleTouchListener() {

				@Override
				public void onSingleTouch(int position) {
					NewsAdTO to = mAdAdapter.getItemAtPosition(position);
					NewsTO newsTO = new NewsTO();
					newsTO.setId(to.getId());
					newsTO.setTitle(to.getTitle());
					newsTO.setImage(to.getImage());
					Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
					intent.putExtra(Constants.EXTRA_DATA, newsTO);
					startActivity(intent);
				}
			});
			mListAdapter = new NewsListAdapter(mContext);
			mListView.setAdapter(mListAdapter);
			new NewsCacheLoader(mContext, mNewsListUrl, NewsDataTO.class).execute();
		}
		return contentView;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.menu_square: {
			Intent intent = new Intent(getActivity(), TrendsAllActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.menu_near: {
			Intent intent = new Intent(getActivity(), TrendsNearActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.menu_fishing: {
			Intent intent = new Intent(getActivity(), NearFishingActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.menu_gift: {
			if (!AccountManager.getInstance(mContext).isLogined()) {
				UiUtil.showNoLoginDialog(this, -1, LoginActivity.ACTION_RETURN);
				return;
			}
			Intent intent = new Intent(getActivity(), GiftActivity.class);
			startActivity(intent);
		}
			break;

		default:
			break;
		}
	}

	@Override
	public void onResponse(NewsDataTO response) {
		if (getActivity() != null) {
			super.onResponse(response);
			if (response != null) {
				NewsListTO listTO = response.getNews();
				List<NewsAdTO> newsAdList = null;
				List<NewsTO> newsList = null;
				if (listTO != null) {
					newsAdList = listTO.getAdList();
					newsList = listTO.getNewsList();
				}
				// 第一页
				if (response.getCurrentPage() <= 1) {
					// 保存到本地数据库缓存
					CacheDao.addOrUpdateCache(mContext, mNewsListUrl, response);
					mAdAdapter.clear();
					if (newsAdList == null || newsAdList.isEmpty()) {
						mHeaderView.setVisibility(View.GONE);
					} else {
						mHeaderView.setVisibility(View.VISIBLE);
						mAdAdapter.addNewsAd(newsAdList);
					}
					mAdAdapter.notifyDataSetChanged();
					mIconPageIndicator.notifyDataSetChanged();
					mListAdapter.clear();
				}
				mListAdapter.addNewsAd(newsList);
				mListAdapter.notifyDataSetChanged();
			}
		}
	}

	/**
	 * 加载新闻缓存
	 * 
	 * @author dl1001
	 * 
	 */
	class NewsCacheLoader extends LoadCacheTask<NewsDataTO> {

		public NewsCacheLoader(Context context, String cacheKey, Class<NewsDataTO> clazz) {
			super(context, cacheKey, clazz);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Cache<NewsDataTO> result) {
			super.onPostExecute(result);
			if (result != null && result.getData() != null) {
				onResponse(result.getData());
			}
			startRequest();
		}

	}

	/**
	 * 资讯广告位Adapter
	 * 
	 * @author dl1001
	 * 
	 */
	class NewsAdAdapter extends PagerAdapter implements IconPagerAdapter {

		private List<NewsAdTO> mNews = new ArrayList<NewsAdTO>();

		public void addNewsAd(List<NewsAdTO> list) {
			if (list != null && !list.isEmpty()) {
				mNews.addAll(list);
			}
		}

		public void clear() {
			mNews.clear();
		}

		public NewsAdTO getItemAtPosition(int position) {
			return mNews.get(position);
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			NewsAdTO adTO = mNews.get(position);
			View contentView = View.inflate(mContext, R.layout.news_header_item, null);
			NetworkImageView coverView = ViewHolder.get(contentView, R.id.image);
			String imageUrl = adTO.getImage();
			BitmapBinder.bindNetImage(mContext, coverView, imageUrl, R.drawable.default_image_big, false);
			TextView titleView = ViewHolder.get(contentView, R.id.title);
			titleView.setText(adTO.getTitle());
			container.addView(contentView);
			return contentView;
		}

		@Override
		public int getIconResId(int index) {
			return R.drawable.dot_selector;
		}

		@Override
		public int getCount() {
			return mNews.size();
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

		@Override
		public void destroyItem(ViewGroup collection, int position, Object view) {
			collection.removeView((View) view);
		}

	}

	@Override
	protected BaseGsonRequest<NewsDataTO> getRequest(Listener<NewsDataTO> listener, ErrorListener errorListener) {
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_PAGE_SIZE, String.valueOf(Constants.DEFAULT_PAGE_SIZE));
		params.put(UriHelper.PARAMS_PAGE_NO, String.valueOf(1));
		AccountManager accountManager = AccountManager.getInstance(mContext);
		if (accountManager.isLogined()) {
			UserTO user = accountManager.getUserTO();
			params.put(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
			params.put(UriHelper.PARAMS_TOKEN, user.getToken());
		}
		return new GsonRequest<NewsDataTO>(Method.POST, mNewsListUrl, listener, errorListener, params, NewsDataTO.class);
	}

	@Override
	protected String getEmptyString() {
		return mContext.getString(R.string.no_news_content);
	}

}
